package com.mycat.dfs.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;



import com.mycat.common.util.CommonUtil;

/**
 * 文件操作类型 Created by Administrator on 2016/8/25.
 *
 * @author Roger
 */
public class FileOperation {
	/**
	 * 图片所有类型
	 */
	private static List<String> imageType = new ArrayList<>();

	static {
		imageType.add("bmp");
		imageType.add("gif");
		imageType.add("jpg");
		imageType.add("pic");
		imageType.add("png");
		imageType.add("tif");
	}

	/**
	 * 判断当前扩展名是否为图片
	 *
	 * @param extName
	 *            文件后缀名
	 * @return 为图片时返回true
	 */
	public static boolean isPicture(String extName) {
		if (CommonUtil.isEmpty(extName)) {
			return false;
		}
		return imageType.contains(extName.toLowerCase());
	}

	/**
	 * 压缩图片
	 * 
	 * @param originPicture
	 *            压缩前图片流
	 * @param compressWidth
	 *            压缩后的宽
	 * @param compressHight
	 *            压缩后的高
	 * @param extName
	 *            图片后缀名
	 * @return 压缩后的图片流
	 */
	public static InputStream fixPicture(InputStream originPicture, int compressWidth, int compressHight, String extName) {
		InputStream picture = null;
		BufferedImage tmpImage;
		try {
			BufferedImage image = Thumbnails.of(originPicture).scale(1).asBufferedImage();
			int width = image.getWidth();
			int height = image.getHeight();
			if (width > height) {
				tmpImage = Thumbnails.of(image).sourceRegion(Positions.CENTER, height, height)
						.size(compressWidth, compressHight).keepAspectRatio(false).asBufferedImage();
			} else {
				tmpImage = Thumbnails.of(image).sourceRegion(Positions.TOP_LEFT, width, width)
						.size(compressWidth, compressHight).keepAspectRatio(false).asBufferedImage();
			}
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			ImageIO.write(tmpImage, extName, os);
			picture = new ByteArrayInputStream(os.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return picture;
	}

	/**
	 * 将byte[]转换为图片
	 * 
	 * @param data
	 *            byte[]
	 * @param path
	 *            图片地址,需要包换图片名
	 */
	public static void byteToImage(byte[] data, String path) {
		if (data.length < 3 || path.equals(""))
			return;
		try {
			FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
			imageOutput.write(data, 0, data.length);
			imageOutput.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
